// custom-tab-bar/index.js
Component({
  data: {
    selected: 0,
    showModal: false,
    color: "#6b7280",
    selectedColor: "#10b981",
    // Tab页面配置
    list: [
      {
        pagePath: "/pages/home/home",
        text: "首页"
      },
      {
        pagePath: "/pages/service/service", 
        text: "服务"
      },
      {
        pagePath: "/pages/demand/demand",
        text: "需求"
      },
      {
        pagePath: "/pages/my/my",
        text: "我的"
      }
    ]
  },

  methods: {
    // 切换Tab
    switchTab(e) {
      const data = e.currentTarget.dataset;
      const url = data.path;
      const index = data.index;
      
      // 防止重复点击当前页面
      if (this.data.selected === index) {
        return;
      }

      // 更新选中状态
      this.setData({
        selected: index
      });

      // 切换页面
      wx.switchTab({
        url,
        success: () => {
          // 确保其他页面的TabBar也更新
          this.updateTabBar(index);
        },
        fail: (err) => {
          console.error('切换Tab失败:', err);
          // 恢复原来的选中状态
          this.setData({
            selected: this.data.selected
          });
        }
      });
    },

    // 显示发布弹窗
    showPublishModal() {
      this.setData({
        showModal: true
      });
      
      // 添加触觉反馈
      wx.vibrateShort({
        type: 'light'
      });
    },

    // 隐藏发布弹窗
    hidePublishModal() {
      this.setData({
        showModal: false
      });
    },

    // 阻止事件冒泡
    stopPropagation() {
      // 空方法，用于阻止弹窗内容点击时关闭弹窗
    },

    // 导航到发布页面
    navigateToPublish(e) {
      const type = e.currentTarget.dataset.type;
      let url = '';
      
      if (type === 'service') {
        url = '/pages/publish-service/publish-service';
      } else if (type === 'demand') {
        url = '/pages/publish-demand/publish-demand';
      }

      if (url) {
        wx.navigateTo({
          url,
          success: () => {
            // 关闭弹窗
            this.hidePublishModal();
          },
          fail: (err) => {
            console.error('导航失败:', err);
            wx.showToast({
              title: '页面跳转失败',
              icon: 'error',
              duration: 2000
            });
          }
        });
      }
    },

    // 更新TabBar状态
    updateTabBar(index) {
      // 通知所有TabBar实例更新选中状态
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          selected: index
        });
      }
    },

    // 初始化TabBar状态
    init() {
      // 获取当前页面路径
      const page = getCurrentPages().pop();
      if (page) {
        const route = `/${page.route}`;
        const index = this.data.list.findIndex(item => item.pagePath === route);
        
        if (index !== -1) {
          this.setData({
            selected: index
          });
        }
      }
    }
  },

  // 组件生命周期
  lifetimes: {
    attached() {
      // 组件实例进入页面时执行
      this.init();
    }
  },

  // 页面生命周期
  pageLifetimes: {
    show() {
      // 页面显示时执行
      this.init();
    }
  }
});
